package com.example.service;

import com.example.feign.StockFeignClient;
import com.example.model.Order;
import com.example.repository.OrderDAO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * Description : OrderService
 *
 * @author : Mr.Liang
 * @version : v1.0
 * @date : 2021/11/10
 */
@Service
public class OrderService {

    @Resource
    private OrderDAO orderDAO;

    @Resource
    private StockFeignClient stockFeignClient;

    /**
     * 下单：创建订单、减库存，涉及到两个服务
     *
     * @param userId        用户id
     * @param commodityCode 商品
     * @param count         数量
     */
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    public void placeOrder(String userId, String commodityCode, Integer count) {
        BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
        Order order = new Order()
                .setUserId(userId)
                .setCommodityCode(commodityCode)
                .setCount(count)
                .setMoney(orderMoney);
        //order服务创建订单
        int insert = orderDAO.insert(order);
        System.out.println("创建订单结果 = " + (insert > 0));
        //创建订单后调用库存服务扣减库存
        Boolean deduct = stockFeignClient.deduct(commodityCode, count);
        System.out.println("扣减库存结果 = " + deduct);
        //制造一个异常验证是否回滚 商品1正常下单 商品2的时候模拟异常
        if ("product-2".equals(commodityCode)) {
            int error = 10 / 0;
        }
        //经过验证 异常后 2个服务的数据都有回滚 分布式事务可用
    }
}
